package com.thinkgem.jeesite.modules.biz.web.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.biz.entity.BizGoods;
import com.thinkgem.jeesite.modules.biz.entity.BizGoodsClassify;
import com.thinkgem.jeesite.modules.biz.form.*;
import com.thinkgem.jeesite.modules.biz.service.BizGoodsClassifyService;
import com.thinkgem.jeesite.modules.biz.service.BizGoodsService;
import com.thinkgem.jeesite.modules.biz.vo.BizGoodsClassifyChildVO;
import com.thinkgem.jeesite.modules.biz.vo.BizGoodsClassifyVO;
import com.thinkgem.jeesite.modules.biz.vo.BizGoodsVO;
import com.thinkgem.jeesite.modules.biz.vo.ResultVO;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.enums.ResultEnum;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Description:
 * Author: LTY
 * Create Time: 2018-08-09 14:52
 */
@Controller
@Slf4j
@RequestMapping("${adminPath}/api/biz/bizGoods")
public class BizGoodsApiController extends BaseController {

    @Autowired
    private BizGoodsService bizGoodsService;

    @Autowired
    private SystemService systemService;
    
    @Autowired
    private BizGoodsClassifyService bizGoodsClassifyService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO listForApi(@Valid BizGoodsForm bizGoodsForm, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {

        if (bindingResult.hasErrors()) {
            log.error("【创建订单异常】表单校验参数不正确：orderForm => {}", bizGoodsForm);
            return ResultVOUtil.error(ResultEnum.FORM_VALIDATE_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        ResultVO resultVO = systemService.checkSign(request, BizGoodsForm.class, bizGoodsForm);

        if (resultVO.getCode() == 0) {
            BizGoods bizGoods = new BizGoods();
            BeanUtils.copyProperties(bizGoodsForm, bizGoods);

            List<BizGoodsVO> list = bizGoodsService.findListForApi(bizGoods);
            return ResultVOUtil.success(list);
        }

        return resultVO;

    }


     /**
      * 手机端获取商品详情
      * @author tiancheng
      * @date 2018/8/31 14:16
      * @param
      * @return
      */
    @RequestMapping(value = "get", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO get(@Valid BizGoodsGetForm bizGoodsGetForm, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {

        if (bindingResult.hasErrors()) {
            log.error("【获取商品的详情失败】表单校验参数不正确：orderForm => {}", bizGoodsGetForm);
            return ResultVOUtil.error(ResultEnum.FORM_VALIDATE_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        ResultVO resultVO = systemService.checkSign(request, BizGoodsGetForm.class, bizGoodsGetForm);

        if (resultVO.getCode() == 0) {
            BizGoodsVO bizGoodsVO = bizGoodsService.getApi(bizGoodsGetForm.getGoodsId().toString());
            return ResultVOUtil.success(bizGoodsVO);
        }
        return resultVO;
   }


    /**
     * CRM下单时单个商品的查询
     * @author tiancheng
     * @date 2018/8/31 14:16
     * @param
     * @return
     */
    @RequestMapping(value = "getByCode", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO getByCode(@Valid BizGoodsGetByCodeForm bizGoodsGetByCodeForm, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {

        if (bindingResult.hasErrors()) {
            log.error("【获取商品失败】表单校验参数不正确：bizGoodsGetByCodeForm => {}", bizGoodsGetByCodeForm);
            return ResultVOUtil.error(ResultEnum.FORM_VALIDATE_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        //查询商品编码是否存在，返回可用库存数
        Integer stockAmount = bizGoodsService.getStockAmountByGoodsCode(bizGoodsGetByCodeForm.getCode());
        if(null != stockAmount){
            return ResultVOUtil.success(stockAmount);
        }
        return ResultVOUtil.error(ResultEnum.PRODUCT_NOT_EXIST.getCode(),"商品不存在！");
    }




     /**
      * CRM下单后修改可用库存和代发货数并添加订单
      * @author tiancheng
      * @date 2018/10/4 14:02
      * @param
      * @return
      */
    @RequestMapping(value = "updateStockAmount", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO updateStockAmount(@RequestBody String code,HttpServletRequest request) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            BizOrderForm bizOrderForm = objectMapper.readValue(code, BizOrderForm.class);
            return bizGoodsService.updateInfoNew(bizOrderForm);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultVOUtil.error();
    }



    @RequestMapping(value = "allList", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO allListForApi(@Valid BizGoodsAllListForm bizGoodsAllListForm, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {

        if (bindingResult.hasErrors()) {
            log.error("【获取商品失败】表单校验参数不正确：bizGoodsAllListForm => {}", bizGoodsAllListForm);
            return ResultVOUtil.error(ResultEnum.FORM_VALIDATE_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        ResultVO resultVO = systemService.checkSign(request, BizGoodsAllListForm.class, bizGoodsAllListForm);

        if (resultVO.getCode() == 0) {
            int pageNo = bizGoodsAllListForm.getPageNo();
            int pageSize = bizGoodsAllListForm.getPageSize();
            String classifyId = bizGoodsAllListForm.getClassifyId();
            String searchKey = bizGoodsAllListForm.getSearchKey();
            List<BizGoodsVO> bizGoodsList = bizGoodsService.findAllListForApi(pageNo,pageSize,classifyId,searchKey);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("bizGoodsList",bizGoodsList);
            return ResultVOUtil.success(hashMap);
        }
        return resultVO;
    }

    @RequestMapping(value = "goodsClassify", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO goodsClassify(@Valid BizGoodsClassifyForm bizGoodsClassifyForm, BindingResult bindingResult,
                                  HttpServletRequest request, HttpServletResponse response) {
        if (bindingResult.hasErrors()) {
            log.error("【获取商品分类失败】表单校验参数不正确：bizGoodsClassifyForm => {}", bizGoodsClassifyForm);
            return ResultVOUtil.error(ResultEnum.FORM_VALIDATE_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        ResultVO resultVO = systemService.checkSign(request, BizGoodsClassifyForm.class, bizGoodsClassifyForm);
        if (resultVO.getCode() == 0) {
            //父类List
            List<BizGoodsClassifyVO> bizGoodsClassifyVOS = new ArrayList<>();
            //获取父级商品分类
            List<BizGoodsClassify> parentClassifyList = bizGoodsClassifyService.findAllParentList();
            if(parentClassifyList != null && parentClassifyList.size() > 0){
                for (BizGoodsClassify bizGoodsClassify : parentClassifyList) {
                    if(bizGoodsClassify != null && StringUtils.isNotEmpty(bizGoodsClassify.getId())){
                        //父级对象
                        BizGoodsClassifyVO bizGoodsClassifyVO = new BizGoodsClassifyVO();
                        bizGoodsClassifyVO.setId(bizGoodsClassify.getId());
                        bizGoodsClassifyVO.setName(bizGoodsClassify.getName());
                        List<BizGoodsClassify> childClassifyList = bizGoodsClassifyService.findChildListByPId(bizGoodsClassify.getId());
                        if(childClassifyList != null && childClassifyList.size() > 0){
                            //子集List
                            ArrayList<BizGoodsClassifyChildVO> bizGoodsClassifyChildVOS = new ArrayList<>();
                            for (BizGoodsClassify goodsClassify : childClassifyList) {
                                if(goodsClassify != null && StringUtils.isNotEmpty(goodsClassify.getId())){
                                    //子级对象
                                    BizGoodsClassifyChildVO bizGoodsClassifyChildVO = new BizGoodsClassifyChildVO();
                                    bizGoodsClassifyChildVO.setId(goodsClassify.getId());
                                    bizGoodsClassifyChildVO.setName(goodsClassify.getName());
                                    bizGoodsClassifyChildVOS.add(bizGoodsClassifyChildVO);
                                }
                            }
                            bizGoodsClassifyVO.setChild(bizGoodsClassifyChildVOS);
                        }
                        bizGoodsClassifyVOS.add(bizGoodsClassifyVO);
                    }
                }
            }

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("classifyList",bizGoodsClassifyVOS);
            return ResultVOUtil.success(hashMap);
        }
        return resultVO;
    }
}
